import { createSlice, PayloadAction } from '@reduxjs/toolkit'
import { IEmployee, IPeriod, IProject, IProjectManager } from '../model/interfaces'
import { modalActions } from './modal.slice'

interface ITmpState {
  period: IPeriod | null
  selectedPeriods: IPeriod[]
  doRemovePeriods: IPeriod[]
  employee: IEmployee
  project: IProject
  projectManager: IProjectManager
}

const initialState: ITmpState = {
  period: null,
  selectedPeriods: [],
  doRemovePeriods: [],
  employee: {
    _id: '',
    firstName: '',
    lastName: '',
    birthDay: null,
    comment: '',
    config: {},
    isActive: true,
  },
  project: {
    _id: '',
    title: '',
    code: '',
    from: null,
    to: null,
    config: {},
    isActive: true
  },
  projectManager: {
    _id: '',
    firstName: '',
    lastName: '',
    birthDay: null,
    comment: '',
    config: {},
    isActive: true,
  }
}

export const tmpSlice = createSlice({
  name: 'tmp',
  initialState,
  reducers: {
    setTmpPeriod(state, action: PayloadAction<IPeriod | null>) {
      state.period = action.payload
    },
    setSelectedTmpPeriods(state, action: PayloadAction<IPeriod[]>) {
      state.selectedPeriods = action.payload
    },
    setDoRemoveTmpPeriods(state, action: PayloadAction<IPeriod[]>) {
      state.doRemovePeriods = action.payload
    },
    setTmpEmployee(state, { payload }:PayloadAction<IEmployee>) {
      state.employee = payload
    },
    setTmpProjectManager(state, { payload }:PayloadAction<IProjectManager>) {
      state.projectManager = payload
    },
    setTmpProject(state, { payload }:PayloadAction<IProject>) {
      state.project = payload
    }
  },
  extraReducers: (builder) => {
    builder.addMatcher(modalActions.onShowModal.match, (state, {payload}) => {
      if (!payload) {
        state.period = initialState.period
        state.selectedPeriods = initialState.selectedPeriods
        state.doRemovePeriods = initialState.doRemovePeriods
        state.employee = initialState.employee
        state.project = initialState.project
        state.projectManager = initialState.projectManager
      }

    })
  }
})

export const tmpActions = tmpSlice.actions
export const tmpReducer = tmpSlice.reducer
